package com.asset.filter;
/**
 *@ClassName LoginFilter
 *@Author B21015118吴逸鑫
 *@Date 2022/6/9 08:10
 **/


import com.asset.bean.User;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class LoginFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) {

    }
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpSession session = request.getSession();
        User user =(User) session.getAttribute("user");
        String path = request.getServletPath();
        //不需要过滤的url
        String[] urls = {"/AdminLoginServlet","/LoginServlet", "/RegisterServlet", "/json", ".js", ".css", ".ico", ".jpg", ".png"};
        // flag是登录成功标志
        boolean flag = true;
        for (String url : urls) {
            if (path.contains(url) && !path.contains(".jsp")) {
                flag = false;
                break;
            } else if ( path.contains("login.jsp") || path.contains("register.jsp") ) {
                flag = false;
                break;
            }
        }
        if (flag) {
            if (user != null) {
                filterChain.doFilter(request, response);
            } else {
                response.sendRedirect("login.jsp");
            }
        } else {
            filterChain.doFilter(request, response);
        }
    }
    @Override
    public void destroy() {

    }
}

